package com.shr.lease.web.admin.controller.login;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shr.lease.common.context.LoginUserContext;
import com.shr.lease.common.exception.LeaseException;
import com.shr.lease.common.result.Result;
import com.shr.lease.common.result.ResultCodeEnum;
import com.shr.lease.common.utils.JWTUtil;
import com.shr.lease.model.entity.SystemUser;
import com.shr.lease.model.enums.BaseStatus;
import com.shr.lease.web.admin.service.LoginService;
import com.shr.lease.web.admin.service.SystemUserService;
import com.shr.lease.web.admin.vo.login.CaptchaVo;
import com.shr.lease.web.admin.vo.login.LoginVo;
import com.shr.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.shr.lease.web.admin.vo.system.user.SystemUserItemVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

@Tag(name = "后台管理系统登录管理")
@RestController
@RequestMapping("/admin")
public class LoginController {

    @Resource
    private LoginService loginService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SystemUserService systemUserService;

    @Operation(summary = "获取图形验证码")
    @GetMapping("login/captcha")
    public Result<CaptchaVo> getCaptcha() {
        CaptchaVo captcha = loginService.getCaptcha();
        return Result.ok(captcha);
    }

    @Operation(summary = "登录")
    @PostMapping("login")
    public Result<String> login(@RequestBody LoginVo loginVo) {

        //1、参数非空判断
        if (loginVo.getUsername() == null || loginVo.getPassword() == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        if (loginVo.getCaptchaKey() == null || loginVo.getCaptchaKey().isEmpty()
        || loginVo.getCaptchaCode() == null || loginVo.getCaptchaCode().isEmpty() ){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //2、判断验证码是否已过期
        String captcha = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (captcha == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //3、判断验证码是否正确
        if(!captcha.equals(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //4、判断是否存在用户
        SystemUser systemUser = systemUserService.getOne(
                new LambdaQueryWrapper<SystemUser>()
                        .eq(SystemUser::getUsername, loginVo.getUsername())
        );
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //5、判断用户状态
        if (systemUser.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //6、判断密码是否正确
        if (!DigestUtils.sha256Hex(loginVo.getPassword()).equals(systemUser.getPassword())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //7、创建JWT返回
        return Result.ok(JWTUtil.generateToken(systemUser.getId(), loginVo.getUsername()));
    }

    @Operation(summary = "获取登陆用户个人信息")
    @GetMapping("info")
    public Result<SystemUserInfoVo> info() {
        Long userId = LoginUserContext.getLoginUser().getUserId();

        SystemUser systemUser = systemUserService.getOne(
                new LambdaQueryWrapper<SystemUser>()
                        .select(SystemUser::getName,
                                SystemUser::getAvatarUrl)
                        .eq(SystemUser::getId, userId)
        );
        return Result.ok(
                SystemUserInfoVo.builder()
                        .name(systemUser.getName())
                        .avatarUrl(systemUser.getAvatarUrl())
                .build()
        );
    }
}